package com.dingtalk.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/robot")
public class RobotController {

    @PostMapping("/webhook")
    public Map<String, Object> receiveMessage(@RequestBody String body) {
        log.info("收到钉钉消息原文: {}", body);
        
        try {
            // 解析JSON
            JsonObject jsonObject = JsonParser.parseString(body).getAsJsonObject();
            
            // 打印关键信息
            if (jsonObject.has("text") && jsonObject.get("text").isJsonObject()) {
                String content = jsonObject.getAsJsonObject("text").get("content").getAsString();
                log.info("消息内容: {}", content);
            }
            
            if (jsonObject.has("senderNick")) {
                log.info("发送者: {}", jsonObject.get("senderNick").getAsString());
            }
            
            if (jsonObject.has("conversationTitle")) {
                log.info("群名称: {}", jsonObject.get("conversationTitle").getAsString());
            }
            
        } catch (Exception e) {
            log.error("解析消息失败", e);
        }
        
        // 返回成功响应
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "success");
        return response;
    }
    
    /**
     * 验证回调接口（首次配置回调接口时需要）
     */
    @GetMapping("/webhook")
    public Map<String, String> checkUrl(
            @RequestParam(name = "signature", required = false) String signature,
            @RequestParam(name = "timestamp", required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("收到验证请求 - signature: {}, timestamp: {}, nonce: {}, echostr: {}", 
                signature, timestamp, nonce, echostr);
        
        Map<String, String> response = new HashMap<>();
        
        // 如果是钉钉的验证请求，返回 echostr
        if (echostr != null) {
            response.put("success", "true");
            response.put("echostr", echostr);
        } else {
            // 如果是普通访问，返回提示信息
            response.put("success", "true");
            response.put("message", "这是钉钉机器人的回调接口");
        }
        
        return response;
    }
} 